/*****************************************************************************************
   
   Copyright (c) Microsoft Corporation. All rights reserved.

   Use of this code sample is subject to the terms of the Microsoft
   Permissive License, a copy of which should always be distributed with
   this file.  You can also access a copy of this license agreement at:
   http://www.microsoft.com/resources/sharedsource/licensingbasics/permissivelicense.mspx

 ****************************************************************************************/

using System;

namespace GrooveCommands
{
	class GrooveCreateSpace : CommandUtils.GrooveUtilBase
	{
		private string m_Name;
		private string m_CSTURL;
		private string m_GSAPath;
		private string m_GSAPassphrase;
		private bool m_NoMembers;
        private string m_GFSPath;

		[STAThread]
		static void Main(string[] i_Arguments)
		{
			CommandUtils.UtilAppMain.RunApplication(new GrooveCreateSpace(i_Arguments));
		}

		public GrooveCreateSpace(string[] i_Arguments)
			: base (i_Arguments)
		{
			base.UsageMessage = "GrooveCreateSpace [PARAMS...]";
			base.HelpMessage = 
				"GrooveCreateSpace\r\n\t" + 
				"Creates new Groove workspace\r\n" +
				"Parameters:\r\n\t" +
				"/Name=               The display name for the new space\r\n\t" +
                "[/GFSPath            Create a Groove File Sharing workspace at this location]\r\n\t" +
				"[/Account=           The Web Services URI for the Groove account]\r\n\t" +
				"[/Identity=          The Web Services URI for the Groove identity]\r\n\t" +
				"[/CSTURL=            The URL for a create space template]\r\n\t" +
				"[/GSAPath=           The path to the GSA (space archive)file]\r\n\t" +
				"[/GSAPassphrase=     The passphrase used to create the GSA file]\r\n\t" +
				"[/NoMembers          Uninvite (suspended) members of the archive]\r\n\t" +
				"[/RequestKey=        Token used to communicate Groove host]\r\n\t" +
				"[/Host=              The remote Groove host name to issue commands to]\r\n\t" +
				"[/Port=              The remote Groove host port to issue commands to]\r\n\t" +
				"[/Timeout=           Timeout (in ms) for Web Services method execution]\r\n\t" +
				"[/X=                 Configuration file to use for parameter input]\r\n\t" +
				"\r\n";
		}

		public override CheckResult CheckParameters()
		{
			CommandUtils.UtilBase.CheckResult CheckResult = base.CheckParameters();
			if (CheckResult != CommandUtils.UtilBase.CheckResult.Succeeded )
				return CheckResult;
		
			m_Name = base.GetParameterValue("Name");
			if (m_Name == null)
			{
				base.DisplayUsage("You must specify a name for the space.");
				return CommandUtils.UtilBase.CheckResult.Failed;
			}

			m_CSTURL = base.GetParameterValue("CSTURL");
			if (m_CSTURL == null)
				m_CSTURL = "";

			m_GSAPath = base.GetParameterValue("GSAPath");
			if (m_GSAPath != null)
			{
				if (Context.IsLocal && !System.IO.File.Exists(m_GSAPath))
				{
					base.DisplayUsage("Invalid GSAPath!");
					return CommandUtils.UtilBase.CheckResult.Failed;
				}

				m_GSAPassphrase = base.GetParameterValue("GSAPassphrase");
				if (m_GSAPassphrase == null)
				{
					base.DisplayUsage("If you specify a GSAPath, you must specify a GSAPassphrase.");
					return CommandUtils.UtilBase.CheckResult.Failed;
				}
			}

			m_NoMembers = base.GetParameterValueFlag("NoMembers");

            m_GFSPath = base.GetParameterValue("GFSPath");
            if (m_GFSPath != null)
            {
                if (!System.IO.Directory.Exists(m_GFSPath))
                {
                    base.DisplayUsage("GFS Path does not exist. Creating GFS Path.");
                    try
                    {
                        System.IO.Directory.CreateDirectory(m_GFSPath);
                    }
                    catch (System.Exception excep)
                    {
                        base.StandardError.WriteLine("Unable to create GSAPath: " + excep.Message);
                        throw excep;
                    }
                }
            }
            else
            {
                m_GFSPath = "";
            }

			return base.CheckUnusedParameters();
		}

		public override CommandUtils.UtilBase.CheckResult Run()
		{
			string SpaceURI = null;

			try
			{
				if (!String.IsNullOrEmpty(m_GFSPath))
                {
                    SpaceURI = base.Identity.CreateGrooveFileSharingSpace
                        (
                        m_GFSPath,
                        m_Name
                        );
                }
                else if (m_GSAPath != null)
				{
					SpaceURI = base.Identity.CreateSpaceFromGSA
						(
						m_GSAPath,
						m_Name,
						m_GSAPassphrase
						);
				}
				else
				{
					SpaceURI = base.Identity.CreateSpace
						(
						m_Name,
						"",		// Description
						m_CSTURL
						);
				}
			}
			catch (System.Exception Exception)
			{
				base.StandardError.WriteLine("Unable to create space: " + Exception.Message);
				throw Exception;
			}

			if (m_NoMembers)
			{
				// Remove any suspended members of the workspace archive
				// ie. any members other than the current identity

				// First we need the workspace
				GrooveWebServicesV12Helpers.Space Space = null;

				try
				{
					Space = base.Identity.OpenSpace(SpaceURI);
				}
				catch (System.Exception Exception)
				{
					base.StandardError.WriteLine("Unable to open space: " + Exception.Message);
					throw Exception;
				}

				foreach( GrooveWebServicesV12Helpers.Member member in Space.Members )
				{
					if( member.URI != base.IdentityURI )
					{
						// This is not me.  Remove.
						Space.Uninvite( member.URI );
					}
				}
			}

			base.StandardOutput.WriteLine("<Space URI='" + SpaceURI + "'/>");
			return CommandUtils.UtilBase.CheckResult.Succeeded;
		}
	}
}
